/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.log.excel;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.excel.support.ExcelImporter;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.log.entity.IntegralTrainingEntity;
import org.springblade.modules.log.entity.IntegralTrainingLogEntity;
import org.springblade.modules.log.entity.IntegralYearLogEntity;
import org.springblade.modules.log.service.IIntegralLogService;
import org.springblade.modules.log.service.IIntegralTrainingLogService;
import org.springblade.modules.log.service.IIntegralTrainingService;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 教师培训记录台账数据导入类
 *
 * @author junxin
 */
@RequiredArgsConstructor
@Configuration
@Slf4j
public class IntegralTrainingLogImporter implements ExcelImporter<IntegralTrainingLogExcel> {

	private final IIntegralTrainingLogService integralTrainingLogService;
	private final IIntegralTrainingService integralTrainingService;
	private final IIntegralLogService integralLogService;
	@Override
	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	public void save(List<IntegralTrainingLogExcel> dataList) {
		long startTime = System.currentTimeMillis();
		if (dataList.size() > 3000) throw new ServiceException("导入条数不可超过3000条");
		String version = DateUtil.format(new Date(), "yyyyMMddHHmmss");//版本批次
		String year = DateUtil.format(new Date(), "yyyy");//当前年度


		List<IntegralTrainingLogEntity> integralTrainingLogEntityList = new ArrayList<>();

		for (IntegralTrainingLogExcel data:dataList){
			//1.保存导入记录
			//培训台账
			IntegralTrainingEntity integralTrainingEntity = new IntegralTrainingEntity();
			IntegralYearLogEntity integralYearLogEntity = new IntegralYearLogEntity();

			//1.1 查找有无此项目的导入记录
			IntegralTrainingEntity oldIntegralTrainingEntity = integralTrainingService.getOne(Wrappers.<IntegralTrainingEntity>query().lambda()
				.eq(IntegralTrainingEntity::getTrainingNumber, data.getTrainingNumber()));
			if (null != oldIntegralTrainingEntity) return;

			//1.2 放入链表，后面批量保存
			BeanUtil.copyProperties(data, integralTrainingEntity,"id");
			integralTrainingEntity.setVersion(version);
			integralTrainingEntity.setYear(year);
			//保存记录台账
			if (null != data.getTeacherNumber()) integralTrainingEntity.setTeacherNumbers(data.getTeacherNumber());
			if (null != data.getUserNumber()) integralTrainingEntity.setStudentNumbers(data.getUserNumber());
			integralTrainingService.save(integralTrainingEntity);

			Long integralTrainingEntityId=integralTrainingEntity.getId();
			boolean assess = false;
			List<Float> userScoreList = new ArrayList<>();
			if ("有".equals(data.getAssess())) {
				assess = true;
				userScoreList = Arrays.asList(toFloatArray(",", data.getUserScore()));
			}

			if (StringUtils.isNotBlank(data.getTrainingPeriod()))integralYearLogEntity.setPeriod(Float.valueOf(data.getTrainingPeriod()));

			//学员编号
			List<String> stuNumberList = Func.toStrList(data.getUserNumber());
			if (assess) { //如果有考核成绩,则需要比对受训人员的成绩与考核成绩
				for (int i = 0; i < stuNumberList.size(); i++) {
					if (userScoreList.get(i) > Long.parseLong(data.getAssessScore())) {
						userAddIntegral(integralTrainingLogEntityList, stuNumberList.get(i), data,integralTrainingEntityId,version,integralTrainingEntity);
					}
				}
			} else {//如果没有考核,则所有受训人员直接加分
				stuNumberList.forEach(stuNumber -> {
					userAddIntegral(integralTrainingLogEntityList, stuNumber, data,integralTrainingEntityId,version,integralTrainingEntity);
				});
			}

			//老师编号
			Func.toStrList(data.getTeacherNumber()).forEach(teaNumber -> {
				//3.老师添加积分
				userAddIntegral(integralTrainingLogEntityList, teaNumber, data,integralTrainingEntityId,version,integralTrainingEntity);
			});
		}



		//3.批量保存培训台账详细
		if (Func.isNotEmpty(integralTrainingLogEntityList)) integralTrainingLogService.saveBatch(integralTrainingLogEntityList);
		log.info("批量导入完成,耗时{}ms", System.currentTimeMillis() - startTime);
	}


	/**
	 * 用户添加积分
	 */
	@SneakyThrows
	public void userAddIntegral(List<IntegralTrainingLogEntity> integralTrainingLogEntityList,
								 String userNumber, IntegralTrainingLogExcel data,Long integralTrainingEntityId,String version,IntegralTrainingEntity integralTrainingEntity) {

		float integral=0;
		int period=0;
		if (null!=data.getIntegral())integral=data.getIntegral();
		if (null!=data.getTrainingPeriod())period=Integer.parseInt(data.getTrainingPeriod());
		integralLogService.addIntegralImport(integralLogService.generalIntegralByTraining(integralTrainingEntity));

		//培训台账明细
//		IntegralTrainingLogEntity integralTrainingLogEntity = new IntegralTrainingLogEntity();
//		BeanUtil.copyProperties(data, integralTrainingLogEntity,"id");
//		integralTrainingLogEntity.setVersion(version);
//		integralTrainingLogEntity.setTrainingId(integralTrainingEntityId);
//		integralTrainingLogEntity.setUserNumber(userNumber);
//		integralTrainingLogEntity.setIntegral(integral);
//		integralTrainingLogEntity.setPeriod(period);
//		integralTrainingLogEntityList.add(integralTrainingLogEntity);
	}

	public static Float[] toFloatArray(String split, String str) {
		if (StringUtil.isBlank(str)) {
			return new Float[0];
		} else {
			String[] arr = str.split(split);
			Float[] floats = new Float[arr.length];

			for (int i = 0; i < arr.length; ++i) {
				Float v = Func.toFloat(arr[i], (float) 0);
				floats[i] = v;
			}

			return floats;
		}
	}

}
